# -*- coding: utf-8 -*-
# @Time : 2024/2/23 10:32
# @Author : ZH
# @File : 2583.py
# @Software: PyCharm
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def kthLargestLevelSum(self, root, k):
        """
        :type root: Optional[TreeNode]
        :type k: int
        :rtype: int
        """
        if not root: return 0
        data_dict = {}

        def asc(node, level: int = 1):
            if not node: return
            if not data_dict.get(level):
                data_dict[level] = node.val
            else:
                data_dict[level] += node.val
            if node.left:
                asc(node.left, level + 1)
            if node.right:
                asc(node.right, level + 1)
        asc(root)
        # print(data_dict)
        data_list = list(data_dict.values())
        data_list.sort()
        return data_list[::-1][k-1]

